<template>
    <div class="chat-container">
        <div class="chat-card">
            <div class="chat-header">
                <button class="back-btn" title="返回好友列表" @click="goBack">
                    <el-icon>
                        <ArrowLeft />
                    </el-icon>
                </button>
                <div v-if="friendInfo" class="friend-info">
                    <img
                        :alt="friendInfo.username"
                        :src="
                            friendInfo.photo ||
                            'https://www.helloimg.com/i/2024/12/22/6767fd5a3cf23.jpg'
                        "
                        class="friend-avatar"
                    />
                    <div class="friend-details">
                        <h1>{{ friendInfo.username }}</h1>
                        <div class="friend-stats">
                            <span>Lv {{ friendInfo.level }}</span>
                            <span>rating: {{ friendInfo.rating }}</span>
                        </div>
                    </div>
                </div>
                <button class="refresh-btn" title="刷新消息" @click="refreshMessages">
                    <el-icon>
                        <Refresh />
                    </el-icon>
                </button>
            </div>

            <div class="chat-messages">
                <div v-if="loading" class="loading-message">加载中...</div>
                <div v-else-if="messages.length === 0" class="empty-message">
                    暂无消息，发送第一条消息开始聊天吧！
                </div>
                <div v-else class="message-list">
                    <div
                        v-for="message in messages"
                        :key="message.id"
                        :class="{ 'message-self': message.senderId === userStore.id }"
                        class="message-item"
                    >
                        <div v-if="message.senderId !== userStore.id" class="message-avatar">
                            <img
                                :alt="friendInfo?.username"
                                :src="
                                    friendInfo?.photo ||
                                    'https://www.helloimg.com/i/2024/12/22/6767fd5a3cf23.jpg'
                                "
                            />
                        </div>
                        <div class="message-content">
                            <div class="message-text">{{ message.content }}</div>
                            <div class="message-time">{{ formatTime(message.createTime) }}</div>
                        </div>
                        <div v-if="message.senderId === userStore.id" class="message-avatar">
                            <img
                                :src="
                                    userStore.photo ||
                                    'https://www.helloimg.com/i/2024/12/22/6767fd5a3cf23.jpg'
                                "
                                alt="我"
                            />
                        </div>
                    </div>
                </div>
            </div>

            <div class="chat-input-area">
                <textarea
                    v-model="messageInput"
                    placeholder="请输入消息..."
                    @keydown="handleKeyDown"
                ></textarea>
                <button :disabled="!messageInput.trim()" class="send-btn" @click="sendMessage">
                    <el-icon>
                        <Promotion />
                    </el-icon>
                    <span>发送</span>
                </button>
            </div>
        </div>
    </div>
</template>

<script setup>
    import { nextTick, onMounted, onUnmounted, ref } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    import { useUserStore } from '@/stores/user'
    import { ElMessage } from 'element-plus'
    import { ArrowLeft, Promotion, Refresh } from '@element-plus/icons-vue'
    import axios from 'axios'
    import { useWebsocketStore } from '@/stores/websocket'

    const route = useRoute()
    const router = useRouter()
    const userStore = useUserStore()
    const websocketStore = useWebsocketStore()
    const socketUrl = `ws://127.0.0.1:8080/websocket/${userStore.token}`

    // 当前聊天好友的ID
    const friendId = ref(route.query.friendId)
    // 好友信息
    const friendInfo = ref(null)
    // 聊天消息列表
    const messages = ref([])
    // 加载状态
    const loading = ref(false)
    // 消息输入
    const messageInput = ref('')

    // 获取好友信息
    const getFriendInfo = async () => {
        if (!friendId.value) {
            ElMessage.error('好友ID无效')
            await router.push('/friend/')
            return
        }

        try {
            const response = await axios.get(
                `http://127.0.0.1:8080/api/friend-relation/getFriendInfo/`,
                {
                    params: {
                        friendId: friendId.value,
                    },
                    headers: {
                        Authorization: 'Bearer ' + userStore.token,
                    },
                }
            )

            const result = response.data
            if (result.code === 1) {
                friendInfo.value = result.data
            } else {
                ElMessage.error(result.msg || '获取好友信息失败')
                await router.push('/friend/')
            }
        } catch (error) {
            console.error('获取好友信息错误:', error)
            ElMessage.error('获取好友信息失败，请稍后重试')
            await router.push('/friend/')
        }
    }

    // 获取聊天历史
    const getChatHistory = async () => {
        loading.value = true
        try {
            const response = await axios.get(`http://127.0.0.1:8080/api/friend-chat/history/`, {
                params: {
                    friendId: friendId.value,
                },
                headers: {
                    Authorization: 'Bearer ' + userStore.token,
                },
            })

            const result = response.data
            if (result.code === 1) {
                messages.value = result.data || []
                // 滚动到底部
                setTimeout(() => {
                    scrollToBottom()
                }, 100)
            } else {
                ElMessage.error(result.msg || '获取聊天记录失败')
            }
        } catch (error) {
            console.error('获取聊天记录错误:', error)
            ElMessage.error('获取聊天记录失败，请稍后重试')
        } finally {
            loading.value = false
        }
    }

    // 发送消息
    const sendMessage = async () => {
        if (!messageInput.value.trim()) {
            return
        }

        try {
            const response = await axios.post(
                'http://127.0.0.1:8080/api/friend-chat/send/',
                {
                    receiverId: friendId.value,
                    content: messageInput.value,
                },
                {
                    headers: {
                        Authorization: 'Bearer ' + userStore.token,
                    },
                }
            )

            const result = response.data
            if (result.code === 1) {
                // 添加消息到列表
                messages.value.push({
                    id: result.data.id,
                    senderId: userStore.id,
                    receiverId: friendId.value,
                    content: messageInput.value,
                    createTime: result.data.createTime,
                    isRead: false,
                })

                // 通过WebSocket通知对方
                if (websocketStore.socket && websocketStore.socket.readyState === WebSocket.OPEN) {
                    websocketStore.socket.send(
                        JSON.stringify({
                            event: 'message_sent',
                            senderId: userStore.id,
                            receiverId: friendId.value,
                            content: messageInput.value,
                        })
                    )
                }

                // 清空输入框
                messageInput.value = ''

                await nextTick(() => {
                    scrollToBottom()
                })
            } else {
                ElMessage.error(result.msg || '发送消息失败')
            }
        } catch (error) {
            console.error('发送消息错误:', error)
            ElMessage.error('发送消息失败，请稍后重试')
        }
    }

    // 消息时间格式化
    const formatTime = (timeString) => {
        const date = new Date(timeString)
        return date.toLocaleString('zh-CN', {
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
        })
    }

    // 滚动到底部
    const scrollToBottom = () => {
        const chatContainer = document.querySelector('.chat-messages')
        if (chatContainer) {
            chatContainer.scrollTop = chatContainer.scrollHeight
        }
    }

    // 返回好友列表
    const goBack = () => {
        router.push('/friend/')
    }

    // 刷新消息
    const refreshMessages = () => {
        getChatHistory()
    }

    // 处理按回车发送消息
    const handleKeyDown = (event) => {
        if (event.key === 'Enter' && !event.shiftKey) {
            event.preventDefault()
            sendMessage()
        }
    }

    let socket = null

    onMounted(() => {
        socket = new WebSocket(socketUrl)

        socket.onopen = () => {
            console.log('websocket连接成功')
            websocketStore.updateSocket(socket)
        }

        socket.onmessage = (msg) => {
            const data = JSON.parse(msg.data)
            console.log('收到消息:', data)
            if (data.event === 'chat_message') {
                messages.value.push({
                    senderId: data.senderId,
                    receiverId: data.receiverId,
                    content: data.content,
                    createTime: new Date(data.timestamp).toISOString(),
                    isRead: false,
                })
                // 确保DOM更新后滚动到底部
                nextTick(() => {
                    scrollToBottom()
                })
            }
        }

        socket.onclose = () => {
            console.log('websocket连接关闭')
        }

        // 获取好友信息和聊天历史
        getFriendInfo()
        getChatHistory()
    })

    onUnmounted(() => {
        socket.close()
    })
</script>

<style scoped>
    .chat-container {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
        width: 100vw;
    }

    .chat-card {
        width: 800px;
        height: 600px;
        background-color: rgba(0, 0, 0, 0.7);
        border-radius: 12px;
        padding: 20px;
        box-shadow: 0 0 30px rgba(255, 215, 0, 0.3);
        border: 1px solid rgba(255, 215, 0, 0.3);
        color: #fff;
        animation: fadeIn 0.5s ease-in-out;
        transform: scale(1);
        transition: transform 0.3s ease;
        display: flex;
        flex-direction: column;
    }

    .chat-card:hover {
        transform: scale(1.01);
        box-shadow: 0 0 40px rgba(255, 215, 0, 0.5);
    }

    .chat-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-bottom: 15px;
        margin-bottom: 15px;
        border-bottom: 1px solid rgba(255, 215, 0, 0.3);
    }

    .chat-header h1 {
        font-size: 24px;
        color: #ffd700;
        text-shadow: 0 0 10px rgba(255, 215, 0, 0.5);
        margin: 0;
        letter-spacing: 2px;
        max-width: 70%;
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
    }

    .back-btn,
    .refresh-btn {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        border: none;
        background-color: rgba(0, 0, 0, 0.3);
        color: #fff;
        cursor: pointer;
        transition: all 0.3s;
    }

    .back-btn {
        border: 1px solid rgba(144, 147, 153, 0.5);
        color: #909399;
    }

    .back-btn:hover {
        background-color: rgba(144, 147, 153, 0.1);
        transform: translateY(-3px);
    }

    .refresh-btn {
        border: 1px solid rgba(255, 215, 0, 0.5);
        color: #ffd700;
    }

    .refresh-btn:hover {
        background-color: rgba(255, 215, 0, 0.1);
        transform: translateY(-3px);
    }

    .chat-messages {
        flex: 1;
        overflow-y: auto;
        padding: 10px;
        margin-bottom: 15px;
        background-color: rgba(0, 0, 0, 0.3);
        border-radius: 8px;
        display: flex;
        flex-direction: column;
    }

    .chat-messages::-webkit-scrollbar {
        width: 6px;
    }

    .chat-messages::-webkit-scrollbar-track {
        background: rgba(255, 255, 255, 0.1);
        border-radius: 3px;
    }

    .chat-messages::-webkit-scrollbar-thumb {
        background-color: rgba(255, 215, 0, 0.5);
        border-radius: 3px;
    }

    .loading-message,
    .empty-message {
        text-align: center;
        padding: 30px 10px;
        color: rgba(255, 255, 255, 0.5);
        font-style: italic;
        margin: auto;
    }

    .message-list {
        display: flex;
        flex-direction: column;
        gap: 15px;
    }

    .message-item {
        display: flex;
        max-width: 80%;
    }

    .message-self {
        align-self: flex-end;
        flex-direction: row-reverse;
    }

    .message-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        overflow: hidden;
        border: 2px solid rgba(255, 215, 0, 0.5);
        flex-shrink: 0;
    }

    .message-avatar img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .message-content {
        margin: 0 10px;
        display: flex;
        flex-direction: column;
    }

    .message-text {
        padding: 10px 15px;
        border-radius: 12px;
        background-color: rgba(255, 255, 255, 0.1);
        word-break: break-word;
        line-height: 1.5;
    }

    .message-self .message-text {
        background-color: rgba(64, 158, 255, 0.2);
        border: 1px solid rgba(64, 158, 255, 0.3);
    }

    .message-time {
        font-size: 12px;
        color: rgba(255, 255, 255, 0.5);
        margin-top: 5px;
        align-self: flex-end;
    }

    .chat-input-area {
        display: flex;
        gap: 10px;
        padding-top: 15px;
        border-top: 1px solid rgba(255, 215, 0, 0.3);
    }

    .chat-input-area textarea {
        flex: 1;
        background-color: rgba(255, 255, 255, 0.1);
        border: 1px solid rgba(255, 215, 0, 0.3);
        border-radius: 6px;
        padding: 12px 15px;
        color: white;
        font-size: 20px;
        font-family: 'Consolas', serif;
        font-style: italic;
        font-weight: bold;
        transition: all 0.3s;
        resize: none;
        height: 60px;
    }

    .chat-input-area textarea:focus {
        outline: none;
        border-color: #ffd700;
        box-shadow: 0 0 8px rgba(255, 215, 0, 0.6);
    }

    .send-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 5px;
        padding: 0 20px;
        height: 60px;
        border: none;
        border-radius: 6px;
        background-color: #ffd700;
        color: #000;
        font-weight: bold;
        cursor: pointer;
        transition: all 0.3s;
    }

    .send-btn:hover {
        background-color: #ffc000;
        transform: translateY(-3px);
        box-shadow: 0 5px 15px rgba(255, 215, 0, 0.4);
    }

    .send-btn:disabled {
        background-color: #666;
        color: #999;
        cursor: not-allowed;
        transform: none;
        box-shadow: none;
    }

    .friend-info {
        display: flex;
        align-items: center;
        gap: 10px;
        max-width: 60%;
    }

    .friend-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        object-fit: cover;
        border: 2px solid rgba(255, 215, 0, 0.5);
    }

    .friend-details {
        display: flex;
        flex-direction: column;
    }

    .friend-stats {
        display: flex;
        gap: 10px;
        font-size: 12px;
        color: rgba(255, 255, 255, 0.7);
    }

    .friend-stats span {
        display: flex;
        align-items: center;
    }

    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(-20px) scale(0.95);
        }
        to {
            opacity: 1;
            transform: translateY(0) scale(1);
        }
    }
</style>
